package com.jige.jigetodo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jige.jigetodo.common.DeleteRequest;
import com.jige.jigetodo.common.ErrorCode;
import com.jige.jigetodo.constant.CommonConstant;
import com.jige.jigetodo.constant.UserConstant;
import com.jige.jigetodo.exception.ThrowUtils;
import com.jige.jigetodo.mapper.TaskMapper;
import com.jige.jigetodo.model.dto.task.AddTaskRequest;
import com.jige.jigetodo.model.dto.task.QueryTaskRequest;
import com.jige.jigetodo.model.dto.task.UpdateTaskRequest;
import com.jige.jigetodo.model.entity.Task;
import com.jige.jigetodo.model.vo.TaskVO;
import com.jige.jigetodo.service.TaskService;
import com.jige.jigetodo.utils.SqlUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【task(任务管理表)】的数据库操作Service实现
 * @createDate 2025-05-08 22:10:34
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task>
        implements TaskService {

    @Override
    public boolean addTask(AddTaskRequest addTaskRequest, HttpServletRequest request) {
        //  判断用户是否已经登录
        Object attribute = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(attribute == null, ErrorCode.NOT_LOGIN_ERROR);
        String title = addTaskRequest.getTitle();
        Long userId = addTaskRequest.getUserId();
        Date deadTime = addTaskRequest.getDeadTime();

        //  标题title不能重复
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(title), "title", title);
        Task exist = this.getOne(queryWrapper);
        ThrowUtils.throwIf(exist != null, ErrorCode.OPERATION_ERROR, "该任务已存在");

        //  操作数据库
        Task task = new Task();
        task.setTitle(title);
        task.setUserId(userId);
        task.setDeadTime(deadTime);
        return this.save(task);
    }

    /**
     * 更新任务
     *
     * @param updateTaskRequest
     * @param request
     * @return
     */
    @Override
    public boolean updateTask(UpdateTaskRequest updateTaskRequest, HttpServletRequest request) {
        //  判断用户是否登录
        Object attribute = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(attribute == null, ErrorCode.NOT_LOGIN_ERROR);

        String title = updateTaskRequest.getTitle();
        String description = updateTaskRequest.getDescription();
        Long id = updateTaskRequest.getId();
        Integer priority = updateTaskRequest.getPriority();
        Integer status = updateTaskRequest.getStatus();
        Date deadTime = updateTaskRequest.getDeadTime();
        Task task = new Task();

        //  查询任务是否存在
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        task = this.getOne(queryWrapper);
        ThrowUtils.throwIf(task == null, ErrorCode.NOT_FOUND_ERROR);

//        ThrowUtils.throwIf(StrUtil.isBlank(title), ErrorCode.PARAMS_ERROR, "标题不能为空");
//        ThrowUtils.throwIf(StrUtil.isNotBlank(priority), ErrorCode.PARAMS_ERROR, "优先级只能为0,1,2");
//        ThrowUtils.throwIf(StrUtil.isNotBlank(status), ErrorCode.PARAMS_ERROR, "状态只能为0,1,2");

        //  操作数据库
        task.setId(id);
        task.setTitle(title);
        task.setDescription(description);
        task.setPriority(priority);
        task.setStatus(status);
        task.setDeadTime(deadTime);

        return this.updateById(task);
    }


    /**
     * 通过id查询任务
     *
     * @param queryTaskRequest
     * @return
     */
    @Override
    public Task getTaskById(QueryTaskRequest queryTaskRequest) {
        ThrowUtils.throwIf(queryTaskRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        //  通过id查询数据库
        Task task = this.getById(queryTaskRequest);
        ThrowUtils.throwIf(task == null, ErrorCode.NOT_FOUND_ERROR);
        return task;
    }

    /**
     * 通过id查询任务VO
     *
     * @param queryTaskRequest
     * @return
     */
    @Override
    public TaskVO getTaskVOById(QueryTaskRequest queryTaskRequest) {
        Task task = getTaskById(queryTaskRequest);
        return new TaskVO().objToVO(task);
    }

    /**
     * 获取任务列表
     *
     * @return
     */
    @Override
    public List<Task> getTaskList(QueryTaskRequest queryTaskRequest) {
        Long userId = queryTaskRequest.getUserId();
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 获取用户任务列表VO
     *
     * @param queryTaskRequest
     * @return
     */
    @Override
    public List<TaskVO> getTaskVOList(QueryTaskRequest queryTaskRequest) {
        List<Task> taskList = this.getTaskList(queryTaskRequest);

        return taskList.stream()
                .map(task -> new TaskVO().objToVO(task))
                .collect(Collectors.toList());
    }

    /**
     * 分页查询用户列表
     *
     * @param queryTaskRequest
     * @return
     */
    @Override
    public Page<Task> getTaskListByPage(QueryTaskRequest queryTaskRequest) {
        int current = queryTaskRequest.getCurrent();
        int pageSize = queryTaskRequest.getPageSize();

        List<Task> taskList = this.getTaskList(queryTaskRequest);

        if (CollUtil.isEmpty(taskList)) {
            return new Page<>();
        }

        QueryWrapper<Task> queryWrapper = this.getQueryWrapper(queryTaskRequest);
        Long taskCount = this.baseMapper.selectCount(queryWrapper);
        Page<Task> taskPage = new Page<>(current, pageSize, taskCount);
        taskPage.setRecords(taskList);
        taskPage.setTotal(taskCount);
        return taskPage;
    }

    /**
     * 根据id删除单个任务
     *
     * @param deleteRequest
     * @return
     */
    @Override
    public boolean deleteTaskById(DeleteRequest deleteRequest) {
        Long id = deleteRequest.getId();
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        //  操作数据库
        return this.removeById(id);
    }

    /**
     * 获取查询条件
     *
     * @param queryTaskRequest
     * @return
     */
    @Override
    public QueryWrapper<Task> getQueryWrapper(QueryTaskRequest queryTaskRequest) {
        ThrowUtils.throwIf(queryTaskRequest == null, ErrorCode.PARAMS_ERROR);
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        Long id = queryTaskRequest.getId();
        String title = queryTaskRequest.getTitle();
        String description = queryTaskRequest.getDescription();
        Long userId = queryTaskRequest.getUserId();
        Integer priority = queryTaskRequest.getPriority();
        Integer status = queryTaskRequest.getStatus();
        String sortField = queryTaskRequest.getSortField();
        String sortOrder = queryTaskRequest.getSortOrder();

//        queryWrapper.eq(id > 0, "id", "id");
        queryWrapper.eq("id", "id");
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.like(StrUtil.isNotBlank(description), "description", description);
//        queryWrapper.eq(userId > 0, "userId", userId);
        queryWrapper.eq("userId", userId);
//        queryWrapper.eq(priority >= 0, "priority", priority);
        queryWrapper.eq("priority", priority);
//        queryWrapper.eq(status >= 0, "status", status);
        queryWrapper.eq("status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        return queryWrapper;
    }
}




